package com.handpay.zztong.hp;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.Account;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.paymentbill.model.Bill;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.paymentbill.activity.QueryBillsActivity;
import com.handpay.zztong.hp.protocol.AQProtocolConstant;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.protocol.ICCardConstant;
import com.handpay.zztong.hp.swiper.SwiperUtils;
import com.handpay.zztong.hp.utils.AccountUtils;

import java.text.ParseException;
import java.util.Hashtable;

import se.krka.kahlua.vm.LuaTable;

/**
 * 转出卡实名认证
 *
 * @author jjyang
 */
public class RealNameAuthentication extends ZZTongActivity {

    public static final String OUT_CARD_NO = "cardNum";// 转出卡
    public static final String OUT_AMOUNT = "amount";// 转出金额
    public static final String TerminlId = "terminalId";
    public static final String ChannelOrderAmt = "channelOrderAmt";
    public static final String EncryAmt = "encryAmt";
    public static final String ChannelOrderCurrency = "channelOrderCurrency";
    public static final String EncryCurrency = "encryCurrency";
    public static final String AccountNumber1 = "accountNumber1";
    public static final String Pan = "pan";
    public static final String Track2Data = "track2Data";
    public static final String DynamicKeyData = "dynamicKeyData";
    public static final String AccountNumber2 = "accountNumber2";
    public static final String HP_encData = "encData";
    public static final String TOTAL = "tatal";
    public static final String TransferInAccount = "mTransferInAccount";
    private Account mTransferInAccount;
    public static final String ICNUM = "icnum";
    public static final String DCDATA = "dcdata";
    public static final String ExpireDate = "expireDate";
    private CheckBox isSave;
    private RealNameAuthentication mContext;
    private String isTurnOn = "1";
    private EditText householderID, householderName, householderPhone;
    private TextView transferAmount, transfer_CardNo;
    String hpamount;
    String hpoutCard;
    String hptotal;
    String hpmac;

    @Override
    protected boolean isShownTopBar() {
        return true;
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    public ActionBar getActivityActionBar() {
        // leftBar goBack();
        return new ActionBar(this.getString(R.string.transfer_card_authentication), true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.real_name_authentication);
        super.onCreate(savedInstanceState);
        mContext = this;

        isSave = (CheckBox) findViewById(R.id.isSave);
        isSave.setChecked(true);
        isSave.setOnClickListener(this);

        hpamount = getIntent().getStringExtra(OUT_AMOUNT);
        hpoutCard = getIntent().getStringExtra(OUT_CARD_NO);
        hptotal = getIntent().getStringExtra(TOTAL);
        hpmac = getIntent().getStringExtra(HP_encData);
        transfer_CardNo = (TextView) findViewById(R.id.transfer_CardNo);
        transfer_CardNo.setText(CommonUtils.formattingCard_4(hpoutCard));
        transferAmount = (TextView) findViewById(R.id.transferAmount);
        transferAmount.setText(CommonUtils.formatMoney(Double.parseDouble(hptotal) / 100));
        householderName = (EditText) findViewById(R.id.householder_name);
        householderID = (EditText) findViewById(R.id.householder_ID_number);
        householderPhone = (EditText) findViewById(R.id.householder_phone_number);

        findViewById(R.id.realNameAuthenticationbt).setOnClickListener(this);

        final Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle == null) {
            goBack();
        }
        this.mAction = getIntent().getByteExtra(ACTION, Action_SuperTransfer);
        HPLog.e("RealNameAuthentication", "mAction----" + mAction);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v != null) {
            int i = v.getId();
            if (i == R.id.isSave) {
                if (isSave.isChecked()) {
                    isTurnOn = "1";

                } else {
                    isTurnOn = "0";
                }

            } else if (i == R.id.realNameAuthenticationbt) {
                if (CheckedValues()) {
                    isSaveAuthentication();
                }

            }
        }
    }

    /***
     * 检查数据值是否合规
     *
     * @return
     */
    private boolean CheckedValues() {
        // 检查用户名的是否符合要求
        String userName = householderName.getText().toString();
        if (!CommonUtils.isRealName(userName)) {
            Toast.makeText(this, R.string.input_right_user_name_tip, Toast.LENGTH_SHORT).show();
            return false;
        }
        // 检查身份证是否符合要求
        String idNo = householderID.getText().toString().trim();
        try {
            if (CommonUtils.IDCardValidate(idNo, true) != null) {
                Toast.makeText(this, R.string.input_right_id_no_tip, Toast.LENGTH_SHORT).show();
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 检查手机号是否符合要求
        if (!CommonUtils.isMobileNum(householderPhone.getText().toString().trim())) {
            Toast.makeText(this, R.string.input_right_phone_tip, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void isSaveAuthentication() {
        Hashtable<String, String> params = new Hashtable<String, String>();

        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        // csn
        String csn = SwiperUtils.getCsn();
        params.put(ATProtocolConstant.CSN_KEY, csn);
        params.put("cardNum", SecureManager.getInstance().des(hpoutCard, 1, null));
        params.put("idNum", SecureManager.getInstance().des(householderID.getText().toString().trim(), 1, null));
        params.put("mobileNum", SecureManager.getInstance().des(householderPhone.getText().toString(), 1, null));
        params.put("userName", SecureManager.getInstance().des(householderName.getText().toString().trim(), 1, null));
        params.put("isSave", isTurnOn);
        this.doPost(this, Do_AddHXFourElements, params);
    }

    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        if (action.equals(Do_AddHXFourElements)) {
            boolean result = super.netResponse(action, resp, showAlert);
            if (result == true) {
                this.setResult(Activity.RESULT_CANCELED);
                this.closeProgressDialog();
                return true;
            }
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            Object rc = luaTable.rawget("responseCode");
            String errMessage = (String) luaTable.rawget("errMessage");
            int isResponseCode = -1;
            if (rc != null) {
                if (rc instanceof String) {
                    isResponseCode = Integer.parseInt((String) rc);
                } else {
                    isResponseCode = ((Double) rc).intValue();
                }
            }
            if (isResponseCode == 0) {
                String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
                if (!TextUtils.isEmpty(address)) {
                    gotosuperTransfer(getIntent().getStringExtra(HP_encData));
                } else {
                    getCurrentLocation();
                }
            } else {

                showAlertDialog(this, getString(R.string.tip), errMessage, true, null);
            }

        } else if (action.equals(Do_SubatmTransfer)) {
            if (super.netResponse(action, resp, showAlert, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    HPLog.i("-------", "onClick!");
                    RealNameAuthentication.this.goBack();
                    dialog.dismiss();
                }
            })) {
                return true;
            }
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            Bill b = CommonUtils.generateBill(luaTable, Bill.APPCODE.SUPER_TRANS);
            // yanglun to do
            HPLog.i(HPLog.SSX_TAG, b.toString());
            if (Bill.STATUS_FAILED == b.getStatus()) {
                Intent intent = new Intent();
                intent.setClass(this, TradingResultsFailed.class);
                intent.putExtra(TradingResults.KEY_NAME, getIntent().getStringExtra(TradingResults.KEY_NAME));
                if (mAction == Action_CreditCardRepay) {
                    intent.putExtra(ACTION, Action_CreditCardRepay);
                } else {
                    intent.putExtra(ACTION, Action_SuperTransfer);
                }
                intent.putExtra(QueryBillsActivity.billvalue, b);
                startActivity(intent);
                onClick(null);
            } else {
                Intent intent = new Intent();
                intent.setClass(this, TradingResults.class);
                intent.putExtra(TradingResults.KEY_NAME, getIntent().getStringExtra(TradingResults.KEY_NAME));
                if (mAction == Action_CreditCardRepay) {
                    intent.putExtra(ACTION, Action_CreditCardRepay);
                } else {
                    intent.putExtra(ACTION, Action_SuperTransfer);
                }
                intent.putExtra(QueryBillsActivity.billvalue, b);
                startActivity(intent);
                onClick(null);
            }

        } else if (action.equals(Do_ZztNewVerifyVersion)) {
            super.netResponse(action, resp, showAlert);
        }
        return true;
    }

    /**
     * 用户实民认证后 去消费
     *
     * @param encMac
     */
    private void gotosuperTransfer(String encMac) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        HPLog.e("zztTransfer", "superTransfer");
        // 刷卡器加密:
        params.put("terminalId", getIntent().getStringExtra(TerminlId));
        // 交易时间
        String time = getFactorTime();
        params.put("transTime", time);
        // 订单总额，des加密
        params.put("channelOrderAmt", SecureManager.getInstance().des(hptotal, 1, null));
        // 订单总额，刷卡器加密
        params.put("encryAmt", getIntent().getStringExtra(EncryAmt));
        // 交易币种
        params.put("channelOrderCurrency", getIntent().getStringExtra(ChannelOrderCurrency));
        // 交易币种，刷卡器加密
        params.put("encryCurrency", getIntent().getStringExtra(EncryCurrency));
        // 转出卡明文Des加密
        params.put("cardNum", SecureManager.getInstance().des(getIntent().getStringExtra(OUT_CARD_NO), 1, null));
        // 转出卡明文刷卡器加密
        params.put("accountNumber1", getIntent().getStringExtra(AccountNumber1));
        // 转出卡密码刷卡器加密
        params.put("pan", getIntent().getStringExtra(Pan));
        // 刷卡器获取
        String track2 = getIntent().getStringExtra(Track2Data);
        String icNum = getIntent().getStringExtra(ICNUM);
        String dcData = getIntent().getStringExtra(DCDATA);
        String expireDate = getIntent().getStringExtra(ExpireDate);
        // 貌似ic插卡，有可能拿到磁道信息？
        if (!TextUtils.isEmpty(track2)) {
            params.put("track2Data", track2);
            // 刷卡器获取
            params.put("dynamicKeyData", getIntent().getStringExtra(DynamicKeyData));
        }
        if (!TextUtils.isEmpty(dcData)) {
            params.put(ICCardConstant.DC_DATA_KEY, dcData);
            if (!TextUtils.isEmpty(icNum)) {
                params.put(ICCardConstant.IC_NUM_KEY, icNum);
            }
        }
        HPLog.e(HPLog.FDL_TAG, "---------RealNameAuthenApplication--------");
        if (!TextUtils.isEmpty(expireDate) && CommonUtils.isLegalExpireDate(expireDate)) {

            // if (!checkExpireDate(expireDate)) {
            // finishDialog(getString(R.string.ic_expire_date_error));
            // return;
            // }
            HPLog.e(HPLog.FDL_TAG, "-RealNameAuthenApplication------expireDate----------" + expireDate);
            params.put("expireDate", SecureManager.getInstance().des(expireDate, 1, null));
        }
        // 转入账号明文DES加密
        params.put("acccountNum", SecureManager.getInstance().des(getIntent().getStringExtra(TransferInAccount), 1, null));
        // 转入账号，刷卡器加密
        params.put("accountNumber2", getIntent().getStringExtra(AccountNumber2));
        // 转账费率fee，des 加密
        Double total = Double.parseDouble(hptotal);
        Double amount = Double.parseDouble(hpamount);
        Double fee = total - amount;
        params.put("fee", SecureManager.getInstance().des(String.valueOf(fee.intValue()), 1, null));
        // csn des加密
        String csn = SwiperUtils.getCsn();
        String cardSerialNumber = SecureManager.getInstance().des(csn, 1, null);
        // csn des加密
        params.put("cardSerialNumber", cardSerialNumber);
        // 收款人姓名
        params.put("accountName", SecureManager.getInstance().des(getIntent().getStringExtra(TradingResults.KEY_NAME), 1, null));
        // channel
        params.put("channel", ClientEngine.CHANNEL);
        params.put(AQProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        // 位置信息
        appendAddresses(params, true);
        // 账户名
        String desAcc = SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null);
        params.put(ATProtocolConstant.ACCOUNT, desAcc);
        // Mac加密
        params.put("mac", encMac);
        doPost(this, Do_SubatmTransfer, params);
    }

    @Override
    public void onSwiperPlugOff() {
        // 回到HPFunction界面
        onFunctionTab(null);
    }
}
